<script setup>
import Toast from '@vant/weapp/dist/toast/toast';
import myCanvas from '@/utils/myCanvas.js'

import { ref, watch, onMounted, getCurrentInstance } from 'vue'

const props = defineProps({
    imageFailPath: {
        type: String,
        default: ''
    },
    queryInfo: {
        type: Object,
        default: () => ({})
    },
})

const emit = defineEmits('update:imageFailPath')


const instance = getCurrentInstance()

// 是否展示
const show = ref(false)


const queryParams = ref({
    imageFileUrl: '', // 图片地址
})

let imgCanvas, rectCanvas = null

// 父盒子宽高
const contentDom = ref({})
// 盒子宽高
const imgRect = ref({})
// 默认矩形信息
const defaultRect = ref({
    x: 50,
    y: 50,
    width: 300,
    height: 200,
    dragging: false,
    resizingCorner: null,
})

// 矩形信息
const rect = ref({
    x: 50,
    y: 50,
    width: 300,
    height: 200,
    dragging: false,
    resizingCorner: null,
})
// 手指位置
const mousePos = ref({ x: 0, y: 0 })


watch(() => props.imageFailPath, val => {
    if (val) {
        calculatePicAspectRatio(val).then(() => {
            rect.value = Object.assign({}, defaultRect.value)
            loadDrawImageFn()
            show.value = true
        })
    }
}, { deep: true })



// 导出canvas图片
function exportCanvasImage() {
    return new Promise(resolve => {
        uni.canvasToTempFilePath({
            canvas: imgCanvas.canvas,
            x: rect.value.x,
            y: rect.value.y,
            width: rect.value.width,
            height: rect.value.height,
            success(res) {
                console.log(res.tempFilePath, '导出图片成功');
                queryParams.value.imageFileUrl = res.tempFilePath
                resolve()
            },
            fail(err) {
                console.log(err, '导出图片失败');
                Toast.fail('导出图片失败')
            },
        })
    })
}


// 处理手指按下事件
function onTouchStart(e) {
    const touch = e.touches[0]
    const offsetX = touch.clientX - (contentDom.value.left || 0)
    const offsetY = touch.clientY - (contentDom.value.top || 0)
    mousePos.value = { x: offsetX, y: offsetY }


    // 检查是否点击在矩形的四个角
    const corners = [
        { x: rect.value.x, y: rect.value.y }, // 左上角
        { x: rect.value.x + rect.value.width, y: rect.value.y }, // 右上角
        { x: rect.value.x, y: rect.value.y + rect.value.height }, // 左下角
        { x: rect.value.x + rect.value.width, y: rect.value.y + rect.value.height }, // 右下角
    ]

    for (let i = 0; i < corners.length; i++) {
        const corner = corners[i]
        // 判断鼠标是否点击在角点附近
        if (Math.abs(offsetX - corner.x) < 20 && Math.abs(offsetY - corner.y) < 20) {
            rect.value.resizingCorner = i // 设置当前调整的角点索引
            return
        }
    }

    // 检查是否点击在矩形内部
    if (
        offsetX > rect.value.x &&
        offsetX < rect.value.x + rect.value.width &&
        offsetY > rect.value.y &&
        offsetY < rect.value.y + rect.value.height
    ) {
        rect.value.dragging = true // 设置拖动状态
    }
}

// 处理手指移动事件
function onTouchMove(e) {
    const touch = e.touches[0]
    const offsetX = touch.clientX - contentDom.value.left || 0
    const offsetY = touch.clientY - contentDom.value.top || 0
    const dx = offsetX - mousePos.value.x
    const dy = offsetY - mousePos.value.y
    mousePos.value = { x: offsetX, y: offsetY }

    const minWidth = 100
    const minHeight = 60


    if (rect.value.resizingCorner !== null) {
        // 调整矩形大小
        switch (rect.value.resizingCorner) {
            case 0: // top-left
                rect.value.x = Math.max(0, Math.min(rect.value.x + dx, rect.value.x + rect.value.width - minWidth))
                rect.value.y = Math.max(0, Math.min(rect.value.y + dy, rect.value.y + rect.value.height - minHeight))
                rect.value.width = Math.max(rect.value.width - dx, minWidth)
                rect.value.height = Math.max(rect.value.height - dy, minHeight)
                break
            case 1: // top-right
                rect.value.y = Math.max(0, Math.min(rect.value.y + dy, rect.value.y + rect.value.height - minHeight))
                rect.value.width = Math.min(Math.max(rect.value.width + dx, minWidth), contentDom.value.width - rect.value.x)
                rect.value.height = Math.max(rect.value.height - dy, minHeight)
                break
            case 2: // bottom-left
                rect.value.x = Math.max(0, Math.min(rect.value.x + dx, rect.value.x + rect.value.width - minWidth))
                rect.value.width = Math.max(rect.value.width - dx, minWidth)
                rect.value.height = Math.min(Math.max(rect.value.height + dy, minHeight), contentDom.value.height - rect.value.y)
                break
            case 3: // bottom-right
                rect.value.width = Math.min(Math.max(rect.value.width + dx, minWidth), contentDom.value.width - rect.value.x)
                rect.value.height = Math.min(Math.max(rect.value.height + dy, minHeight), contentDom.value.height - rect.value.y)
                break
        }

        // 边界判断
        rect.value.x = Math.max(0, Math.min(rect.value.x, contentDom.value.width - rect.value.width))
        rect.value.y = Math.max(0, Math.min(rect.value.y, contentDom.value.height - rect.value.height))
    } else if (rect.value.dragging) {
        // 拖动矩形
        rect.value.x = Math.max(0, Math.min(rect.value.x + dx, contentDom.value.width - rect.value.width))
        rect.value.y = Math.max(0, Math.min(rect.value.y + dy, contentDom.value.height - rect.value.height))
    }

    drawRect()
}

// 处理鼠标松开事件
function onTouchEnd() {
    rect.value.dragging = false
    rect.value.resizingCorner = null
}



// 绘制矩形
function drawRect() {
    rectCanvas.clearRect(0, 0, contentDom.value.width, contentDom.value.height);
    rectCanvas.drawBorderedRect(0, 0, contentDom.value.width, contentDom.value.height, {
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
    });

    // 清空矩形中间的区域
    rectCanvas.clearRect(rect.value.x, rect.value.y, rect.value.width, rect.value.height);
    rectCanvas.drawDraggableBorderedRect(rect.value.x, rect.value.y, rect.value.width, rect.value.height);
}

// 绘制图片
function loadDrawImageFn() {
    const x = (contentDom.value.width - imgRect.value.width) / 2;
    const y = (contentDom.value.height - imgRect.value.height) / 2;

    imgCanvas.drawImage(props.imageFailPath, x, y, imgRect.value.width, imgRect.value.height, undefined, () => {
        rect.value.x = (contentDom.value.width - rect.value.width) / 2;
        rect.value.y = (contentDom.value.height - rect.value.height) / 2;

        rectCanvas.clearRect(0, 0, contentDom.value.width, contentDom.value.height);
        rectCanvas.drawBorderedRect(0, 0, contentDom.value.width, contentDom.value.height, {
            backgroundColor: 'rgba(0, 0, 0, 0.5)',
        });

        // 清空矩形中间的区域
        rectCanvas.clearRect(rect.value.x, rect.value.y, rect.value.width, rect.value.height);
        rectCanvas.drawDraggableBorderedRect(rect.value.x, rect.value.y, rect.value.width, rect.value.height);
    });
}





// 计算图片宽高比及外部边框盒子的宽高
async function calculatePicAspectRatio(path) {
    const { width, height } = await uni.getImageInfo({ src: path })

    const widthRatio = contentDom.value.width / width;
    const heightRatio = contentDom.value.height / height;
    const scaleRatio = Math.min(widthRatio, heightRatio);

    // 计算缩放后的图片宽度和高度
    const scaledWidth = width * scaleRatio;
    const scaledHeight = height * scaleRatio;

    // 绘制尺寸
    imgRect.value = {
        width: scaledWidth,
        height: scaledHeight
    }
}


// 返回
function backFn() {
    show.value = false
    emit('update:imageFailPath', '')
    rectCanvas.clearRect(0, 0, contentDom.value.width, contentDom.value.height);
    imgCanvas.clearRect(0, 0, contentDom.value.width, contentDom.value.height);
}

// 确认
async function confirm() {
    await exportCanvasImage()
    const data = Object.assign({}, queryParams.value, { title: props.queryInfo.title })
    uni.navigateTo({
        url: `/newEditionDraw/takePhotosAnswer/detail/index?data=${JSON.stringify(data)}`,
    })
}

onMounted(() => {
    uni.createSelectorQuery().in(instance).select('.canvas_box').boundingClientRect((res) => {
        // canvas宽高
        contentDom.value = res
        contentDom.value.top = 0
        contentDom.value.left = 0
        rectCanvas = new myCanvas('rectCanvas', instance)
        imgCanvas = new myCanvas('imgCanvas', instance)
    }).exec()
})
</script>

<template>
    <div class='imgPrecinct' :class="{ show: show }">
        <div class="canvas_box">
            <canvas type="2d" id="imgCanvas" class="imgCanvas"></canvas>
            <canvas type="2d" id="rectCanvas" class="rectCanvas" @touchstart="onTouchStart" @touchmove.stop="onTouchMove"
                @touchend="onTouchEnd"></canvas>
        </div>
        <div class="footer">
            <div class="footer_placeholder"></div>
            <div class="footer_content">
                <div class="left" @click="backFn">
                    <i class="iconfont ai-icon-fanhui1"></i>
                </div>
                <div class="center" @click="confirm">
                    <i class="iconfont ai-icon-a-shibieleixingqueren"></i>
                </div>
                <div class="right" @click="openFlashlightFn">
                    <!-- <i class="iconfont ai-icon-xuanzhuan"></i> -->
                </div>
            </div>
        </div>
    </div>
</template>

<style lang='scss' scoped>
.imgPrecinct {
    position: fixed;
    top: 0;
    left: 100%;
    z-index: 2;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 1);

    display: flex;
    flex-direction: column;

    &.show {
        left: 0;
    }

    .canvas_box {
        flex: 1;
        position: relative;

        .rectCanvas,
        .imgCanvas {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 100%;
            height: 100%;
        }

        .imgCanvas {
            z-index: 2;
        }

        .rectCanvas {
            z-index: 3;
        }

    }

    .footer {
        .footer_placeholder {
            height: 229rpx;
        }

        .footer_content {
            box-sizing: border-box;
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 229rpx;
            background: var(--a-main-tabNav-bg-color);
            padding: 28rpx 30rpx;

            display: flex;
            align-items: center;
            justify-content: space-evenly;

            .center {
                box-sizing: border-box;
                width: 127rpx;
                height: 127rpx;
                border-radius: 50%;
                background-color: var(--a-main-color);

                display: flex;
                align-items: center;
                justify-content: center;

                .iconfont {
                    font-size: 56rpx;
                    color: var(--a-one-text-color);
                }
            }

            .left,
            .right {
                width: 100rpx;
                height: 100rpx;
                background: rgba(255, 255, 255, 0.2);
                border-radius: 50%;

                display: flex;
                align-items: center;
                justify-content: center;

                &.right {
                    background: transparent;
                }

                .iconfont {
                    font-size: 32rpx;
                    color: var(--a-one-text-color);
                }

                &.active {
                    background: var(--a-main-color);
                }
            }
        }
    }

}
</style>